package com.gitee.faster.redis.storage;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;

import java.time.Duration;

/**
 * @author hongda.li
 */
@SuppressWarnings("unchecked")
public class MemoryRedisDataStorage implements RedisDataStorage {

    private final Cache<String, Object> cache;

    public MemoryRedisDataStorage() {
        this.cache = Caffeine.newBuilder()
                .initialCapacity(2 << 10)
                .maximumSize(Long.MAX_VALUE)
                .expireAfterAccess(Duration.ofDays(1))
                .build();
    }

    @Override
    public <Data> Data query(String name) {
        return (Data) this.cache.getIfPresent(name);
    }

    @Override
    public <Data> void store(String name, Data data) {
        this.cache.put(name, data);
    }

    @Override
    public <Data> Data remove(String name) {
        Data ifPresent = (Data) this.cache.getIfPresent(name);
        if (ifPresent != null) {
            this.cache.invalidate(name);
            return ifPresent;
        } else {
            return null;
        }
    }
}
